import { http } from "./request";

// 添加 uni 和 wx 类型声明
declare const uni: any;
declare const wx: any;

export const getMobileCode = (params: any) =>
  http.get("tms/getMobileCode", params);
export const getProvinceOption = () => http.post("tms/area/getOptions");
//版本检测
export const versionCheck = (params?: any) => http.get("update", params);
export const uploadImg = (file: string, p?: any) => http.upload(file, p);

export const getRegionOption = () => http.get("regionOption");

export const uploadImages = (
  images: string[],
  onSuccess: (uploadedUrls: string[]) => void,
  onFail?: (err: any) => void
) => {
  const uploadPromises = images.map(async (img: any) => {
    const res: any = await uploadImg(img);
    return res[0];
  });

  Promise.all(uploadPromises)
    .then((uploadedUrls: string[]) => {
      onSuccess(uploadedUrls);
    })
    .catch((err: any) => {
      console.error("图片上传失败:", err);
      onFail && onFail(err);
    });
};

// 返回标准 Promise 的函数
export const regeo = (params: any) => {
  // 创建并返回 Promise
  return new Promise((resolve, reject) => {
    // 使用高德地图 API 获取真实地址信息
    console.log("请求真实地址信息，位置参数:", params.location);
    uni.request({
      url: "https://restapi.amap.com/v3/geocode/regeo",
      method: "GET",
      data: { 
        ...params, 
        key: "faada9cbe5680cbb75722df4a00dc8a1",
        extensions: "all",
        output: "json",
        roadlevel: 1,
        homeorcorp: 1,
        poitype: "商务写字楼,住宅小区"
      },
      success: (res: any) => {
        console.log("地理编码响应:", res);
        
        if (res.statusCode === 200 && res.data && res.data.status === '1' && res.data.regeocode) {
          // 成功获取地址
          resolve({
            address_name: res.data.regeocode.formatted_address,
            address_component: res.data.regeocode.addressComponent
          });
        } else {
          // 响应格式不符合预期
          const errorMsg = res.data ? res.data.info || '位置信息获取失败' : '位置信息获取失败';
          console.warn("地理编码失败:", errorMsg);
          reject(new Error(errorMsg));
        }
      },
      fail: (err: any) => {
        console.error("地理编码请求失败:", err);
        reject(err);
      }
    });
  });
};
